package top.broncho.anpods.guide

import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.net.Uri
import android.os.Bundle
import android.os.PowerManager
import android.provider.Settings
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentPagerAdapter
import androidx.lifecycle.lifecycleScope
import androidx.viewpager.widget.ViewPager
import kotlinx.android.synthetic.main.activity_guid.*
import kotlinx.coroutines.launch
import org.jetbrains.anko.dip
import top.broncho.anpods.R
import top.broncho.anpods.permission.requestDrawOverlays
import top.broncho.anpods.util.putBoolean
import kotlin.math.abs

const val NUM_PAGES = 5
const val KEY_APP_FIRST_RUN = "firstRun"

class GuideActivity : AppCompatActivity() {
    private var isOpaque = true
    private var isSwipeDisabled = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_guid)
        viewPager.adapter = GuideAdapter(supportFragmentManager)
        viewPager.setPageTransformer(true, CrossFadePageTransformer())
        viewPager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrollStateChanged(state: Int) {
            }

            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ) {
                if (position == NUM_PAGES - 2 && positionOffset > 0) {
                    if (isOpaque) {
                        viewPager.setBackgroundColor(Color.TRANSPARENT)
                        isOpaque = false
                    }
                } else {
                    if (!isOpaque) {
                        viewPager.setBackgroundResource(R.color.colorBackground)
                        isOpaque = true
                    }
                }
            }

            override fun onPageSelected(position: Int) {
                setIndicator(position)
                skipBtn.visibility = if (position == 0) View.GONE else View.VISIBLE
                isSwipeDisabled = when (position) {
                    1 -> {
                        val isIgnoringBatteryOptimizations = isIgnoringBatteryOptimizations()
                        nextBtn.text =
                            getString(if (isIgnoringBatteryOptimizations) R.string.next_with_arrow else R.string.grant)
                        !isIgnoringBatteryOptimizations
                    }

                    2 -> {
                        val canDrawOverlays = Settings.canDrawOverlays(applicationContext)
                        nextBtn.text =
                            getString(if (canDrawOverlays) R.string.next_with_arrow else R.string.grant)
                        !canDrawOverlays
                    }
                    else -> {
                        false
                    }
                }
                when {
                    position == NUM_PAGES - 2 -> {
                        //skipBtn.visibility = View.GONE
                        nextBtn.visibility = View.GONE
                        doneBtn.visibility = View.VISIBLE
                    }
                    position < NUM_PAGES - 2 -> {
                        //skipBtn.visibility = View.VISIBLE
                        nextBtn.visibility = View.VISIBLE
                        doneBtn.visibility = View.GONE
                    }
                    position == NUM_PAGES - 1 -> endTutorial()
                }
            }

        })
        skipBtn.visibility = View.INVISIBLE
        skipBtn.text = getString(R.string.previous)
        viewPager.setOnTouchListener { _, _ ->
            isSwipeDisabled
        }
        skipBtn.setOnClickListener {
            //endTutorial()
            onBackPressed()
        }
        doneBtn.setOnClickListener {
            endTutorial()
        }
        nextBtn.setOnClickListener {
            when (viewPager.currentItem) {
                0, 5 ->
                    viewPager.setCurrentItem(viewPager.currentItem + 1, true)
                1 ->
                    if (isIgnoringBatteryOptimizations()) {
                        viewPager.setCurrentItem(viewPager.currentItem + 1, true)
                    } else {
                        requestIgnoreBatteryOptimizations()
                    }
                2 -> lifecycleScope.launch {
                    val result = requestDrawOverlays()
                    if (result)
                        viewPager.setCurrentItem(viewPager.currentItem + 1, true)
                }
            }
        }
        buildCircles()
        rootView.setOnApplyWindowInsetsListener { _, insets ->
            bottomBar.setPadding(
                insets.systemWindowInsetLeft,
                0,
                insets.systemWindowInsetRight,
                insets.systemWindowInsetBottom
            )
            // clear this listener so insets aren't re-applied
            rootView.setOnApplyWindowInsetsListener(null)
            insets.consumeSystemWindowInsets()
        }
        putBoolean(KEY_APP_FIRST_RUN, false)
    }

    override fun onResume() {
        super.onResume()
        if (viewPager.currentItem == 1) {
            val isIgnoringBatteryOptimizations = isIgnoringBatteryOptimizations()
            nextBtn.text =
                getString(if (isIgnoringBatteryOptimizations) R.string.next_with_arrow else R.string.grant)
            isSwipeDisabled = !isIgnoringBatteryOptimizations
        }
    }

    private fun buildCircles() {
        val padding = dip(4)
        for (i in 0 until NUM_PAGES - 1) {
            val circle = ImageView(this).apply {
                setImageResource(R.drawable.ic_circle)
                layoutParams = ViewGroup.LayoutParams(
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT
                )
                adjustViewBounds = true
                setPadding(padding, 0, padding, 0)
            }
            circlesContainer.addView(circle)
        }
        setIndicator(0)
    }

    private fun setIndicator(index: Int) {
        if (index < NUM_PAGES) {
            for (i in 0 until NUM_PAGES - 1) {
                val circle = circlesContainer.getChildAt(i) as ImageView
                if (i == index) {
                    circle.alpha = 1f
                } else {
                    circle.alpha = 0.5f
                }
            }
        }
    }

    private fun endTutorial() {
        finish()
        overridePendingTransition(R.anim.abc_fade_in, R.anim.abc_fade_out)
    }

    override fun onDestroy() {
        super.onDestroy()
        viewPager.clearOnPageChangeListeners()
    }

    override fun onBackPressed() {
        if (viewPager.currentItem != 0) {
            viewPager.currentItem = viewPager.currentItem - 1
        }
    }

    private fun isIgnoringBatteryOptimizations(): Boolean {
        val powerManager =
            getSystemService(Context.POWER_SERVICE) as PowerManager
        return powerManager.isIgnoringBatteryOptimizations(packageName)
    }

    private fun requestIgnoreBatteryOptimizations() {
        try {
            val intent = Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS)
            intent.data = Uri.parse("package:$packageName")
            startActivity(intent)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }


    private inner class GuideAdapter(fm: FragmentManager) :
        FragmentPagerAdapter(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) {

        override fun getPageTitle(position: Int): CharSequence = (position + 1).toString()

        override fun getItem(position: Int): Fragment = GuideFragment.newInstance(position)

        override fun getCount(): Int = NUM_PAGES
    }

    inner class CrossFadePageTransformer : ViewPager.PageTransformer {

        override fun transformPage(page: View, position: Float) {
            val pageWidth = page.width

            // val backgroundView = page.findViewById<View>(R.id.welcome_fragment)
            val titleTV = page.findViewById<TextView>(R.id.guideTitleTV)
            val contentTV = page.findViewById<TextView>(R.id.guideContentTV)
            val guideIV = page.findViewById<ImageView>(R.id.guideIV)

            if (-1 < position && position < 1) {
                page.translationX = pageWidth * -position
            }

            if (-1 < position && position < 1 && position != 0f) {
                //page.alpha = 1.0f - abs(position)

                titleTV?.apply {
                    translationX = pageWidth * position
                    alpha = 1.0f - abs(position)
                }
                contentTV?.apply {
                    translationX = (pageWidth * 2 / 3) * position
                    alpha = 1.0f - abs(position)
                }

                guideIV?.apply {
                    translationX = pageWidth / 2 * position
                    alpha = 1.0f - abs(position)
                }
            }
        }
    }

}
